package cn.iocoder.ny.module.mall.processor;

import cn.iocoder.ny.module.mall.controller.admin.product.dto.MallProductListDTO;
import cn.iocoder.ny.module.mall.domain.MallOrder;
import cn.iocoder.ny.module.mall.domain.MallProduct;
import cn.iocoder.ny.module.mall.domain.MallProductSpecification;
import cn.iocoder.ny.module.mall.mapper.MallOrderMapper;
import cn.iocoder.ny.module.mall.service.IMallOrderService;
import cn.iocoder.ny.module.mall.service.impl.MallProductServiceImpl;
import cn.iocoder.ny.module.mall.service.impl.MallProductSpecificationSerivceImpl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.*;

@Component
public class OrderProcessor {

    private final DelayQueue<OrderD> queue = new DelayQueue<>();

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    @Resource
    private  MallOrderMapper mallOrderMapper;

    private final MallProductServiceImpl mallProductService;

    private final MallProductSpecificationSerivceImpl mallProductSpecificationSerivce;

    @Autowired
    @Lazy
    private IMallOrderService iMallOrderService;

    //更新时间
    public OrderProcessor(MallOrderMapper mallOrderMapper, MallProductServiceImpl mallProductService, MallProductSpecificationSerivceImpl mallProductSpecificationSerivce) {
        this.mallOrderMapper = mallOrderMapper;
        this.mallProductService = mallProductService;
        this.mallProductSpecificationSerivce = mallProductSpecificationSerivce;
    }

    @PostConstruct
    public void init() {
        executor.submit(() -> {
            while (true) {
                try {
                    OrderD order = queue.take(); // 阻塞直到有订单可以取出
                    if (order.getDelay(TimeUnit.NANOSECONDS) <= 0) { // 如果订单已过期
                        cancelOrder(order); // 取消订单
                    } else {
                        // 如果订单还未过期，重新放回队列
                        queue.put(order);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
    }

    public void addOrder(OrderD order) {
        queue.add(order);
    }

    private void cancelOrder(OrderD orderD) {
        // 执行取消订单的逻辑
        System.out.println("Order " + orderD.getOrderId() + " has been cancelled due to non-payment.");
        // 这里可以添加更多关于取消订单的业务逻辑
        //如果待支付状态0  可以取消，其他状态不可以取消
//        UpdateWrapper<MallOrder> orderWrapper = Wrappers.update();
//        orderWrapper.eq("status",0);  //这才是更新条件01  //重要备注 可以连写 可以分开写
//        MallOrder mallOrder = new MallOrder();
//        mallOrder.setStatus(10);
//        mallOrder.setId(orderD.getOrderId());
//        mallOrderMapper.update(mallOrder,orderWrapper);

        boolean update = iMallOrderService.lambdaUpdate().
                eq(MallOrder::getId, orderD.getOrderId())
                .eq(MallOrder::getStatus, 0)
                .set(MallOrder::getStatus, 10)
                .update();

        System.out.println("定时器是否更新DB成功 " + orderD.getOrderId() + update);


        //todo 归还库存
        UpdateWrapper<MallProductSpecification> xxWrapper = Wrappers.update();
        //三大数据购买都会有

        Long productid = orderD.getProductId() ;
        Long specid  = orderD.getPspecId();
        Integer quantity = orderD.getQuantity();

        //xxWrapper.eq("product_id",productid).eq("id",specid);

//        MallProductSpecification mallProductSpecification = new MallProductSpecification();
//        mallProductSpecification.setStock(quantity);
//        mallProductSpecification.setProductId(productid);
//        mallProductSpecification.setId(specid);

        //mallProductSpecificationSerivce.update(mallProductSpecification,xxWrapper);  这是直接更新 多少
        MallProductListDTO mallProductListDTO = new MallProductListDTO();
        //当时付款了 多少件

        mallProductListDTO.setStock(String.valueOf(quantity));
        mallProductListDTO.setSpecificationId(specid);
        //还库存
        mallProductSpecificationSerivce.updateProductStockBySQLADD(mallProductListDTO);
    }

    // 确保在应用关闭时停止执行器
    @PreDestroy
    public void shutdown() {
        executor.shutdownNow();
    }
}
